import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'

import { Upload, Icon, message } from 'antd'
import style from './uploadAvatar.css'

class UploadCom extends PureComponent {
  static propTypes = {
    onChange: PropTypes.func,
    value: PropTypes.string
  }
  constructor (props) {
    super(props)

    this.state = {
      loading: false
    }
    this.handleChange = this.handleChange.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 5
    if (!isLt2M) {
      message.error('图片大小 5MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  handleChange (e) {
    console.log('---->', this.props)
    if (e.file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (e.file.status === 'done') {
      this.setState({
        loading: false
      })
      this.props.onChange(e.file.response.data.imageUrl)
    } else {
      this.setState({
        loading: true
      })

      if (!e.file.status) {
        this.setState({
          loading: false
        })
      }
    }
  }

  render () {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className='ant-upload-text'>Upload</div>
      </div>
    )

    const { value } = this.props
    return (
      <>
        <Upload
          withCredentials
          name='file'
          listType='picture-card'
          className='avatar-uploader'
          showUploadList={false}
          action='/file/upload/1.0'
          onChange={this.handleChange}
          beforeUpload={this.beforeUpload}
          headers={{
            token: localStorage.getItem('token') || ''
          }}
        >
          {value ? (
            <img className={style['img']} src={value} alt='avatar' />
          ) : (
            uploadButton
          )}
        </Upload>
      </>
    )
  }
}

export default UploadCom
